package com.jnsw.gps;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;


public class GpsService extends Service {

    public static String GPS_TYPE_XJ = "XJ";
    public static String GPS_TYPE_GPS = "GPS";
//    private Gps gps = null;
    private boolean threadDisable = false;
    private final static String TAG = GpsService.class.getSimpleName();
//    XunjianDatabaseHelper databaseHelper = null;
    int sjjg, taskid, UserId;
    String flag;
    private static LocationManager locationManager;
    LocationListener locationGPSListener, locationNetListener;

    public static Location gpslocation = null;
    public static Context contextService = null;
    public static GpsService serviceInstance = null;
    public static boolean bServiceRunning = false;
    public static boolean bGPSStarted = false;
    public static boolean bStarting = false;
    public double lat = 0;
    public double lon = 0;

    public List<GPSPoint> GpsList = new ArrayList<>();
    public double getLon() {
        return lon;
    }

    public void setLon(double lon) {
        this.lon = lon;
    }

    public double getLat() {
        return lat;
    }

    public void setLat(double lat) {
        this.lat = lat;
    }

    @Override
    public void onCreate() {

        //从常量配置表中查找间隔时间 -- GPS上报时间间隔
        GpsService.contextService = getApplicationContext();
//        databaseHelper = OpenHelperManager.getHelper(CustomApplication.getInstance(), XunjianDatabaseHelper.class);
//        CustomApplication.getInstance().eventBus.register(this);
        bServiceRunning = StartGPSPosition();

        super.onCreate();
    }


    @Override
    public void onDestroy() {
//        threadDisable = true;
//        if (gps != null) {
//            gps.closeLocation();
//            gps = null;
//        }
//        super.onDestroy();

        try {
            bStarting = false;
            bGPSStarted = false;
            bServiceRunning = false;
//            if (bStarting || bGPSStarted) {
//                StopGPS();
//            }
            serviceInstance = null;
            contextService = null;

            if (locationManager != null) {
                if (locationGPSListener != null) {
                    locationManager.removeUpdates(locationGPSListener);
                }
                if (locationNetListener != null) {
                    locationManager.removeUpdates(locationNetListener);
                }
                if (listener != null) {
                    locationManager.removeGpsStatusListener(listener);
                }
            }
            if (locationGPSListener != null) {
                locationGPSListener = null;
            }
            if (locationNetListener != null) {
                locationNetListener = null;
            }
            if (listener != null) {
                listener = null;
            }
        } catch (Exception e) {

        }
        super.onDestroy();
    }

    public static GpsService GetInstance() {
        if (serviceInstance == null) {
            serviceInstance = new GpsService();
        }
        return serviceInstance;
    }

    public boolean StartGPSPosition() {
        Log.d("gpsinfo ", bStarting + " -------" + bGPSStarted);
        if (bStarting) {
            return false;
        }

        if (!bGPSStarted) {
            StartGPS();
        }


        return true;
    }

    private boolean StartGPS() {
        try {

            if (bStarting) {
                return true;
            }
//            Tip.shortTip("正在打开GPS....");//提示消息
//            Toast.makeText(
//                    GpsService.contextService,
//                    "正在打开GPS....",
//                    Toast.LENGTH_SHORT).show();
            bStarting = true;
            locationManager = (LocationManager) GpsService.contextService.getSystemService(Context.LOCATION_SERVICE);
            bGPSStarted = false;

            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_FINE);// ����Ϊ��󾫶�
            criteria.setAltitudeRequired(false);// ��Ҫ�󺣰���Ϣ
            criteria.setBearingRequired(false);// ��Ҫ��λ��Ϣ
            criteria.setCostAllowed(true);// �Ƿ����?��
            criteria.setPowerRequirement(Criteria.POWER_LOW);// �Ե�����Ҫ��
            String provider = locationManager.getBestProvider(criteria, true);
//            ChangLiang changLiang = databaseHelper.get常量配置Dao().queryBuilder().where().eq("常量名称", "GPS上报时间间隔").queryForFirst();
//            String zhi = changLiang.get常量值();
//            sjjg = Integer.parseInt(zhi);

            sjjg =3;

//            if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER))
            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                provider = LocationManager.GPS_PROVIDER;
                locationGPSListener = new MyLocationListner();
                gpslocation = locationManager.getLastKnownLocation(provider); // ͨ��GPS��ȡλ��
                locationManager.requestLocationUpdates(provider, sjjg*1000, 0, locationGPSListener);
//            }else{
                provider = LocationManager.NETWORK_PROVIDER;
                locationNetListener = new MyLocationListner();
                gpslocation = locationManager.getLastKnownLocation(provider); // ͨ��GPS��ȡλ��
//              locationManager.requestLocationUpdates(provider,2000, 50, locationNetListener);
                locationManager.requestLocationUpdates(provider, sjjg*1000, 0, locationNetListener);
            }
            locationManager.addGpsStatusListener(listener);
            bStarting = true;
        } catch (Exception e) {
            bStarting = false;
            bGPSStarted = false;
//            Tip.shortTip(e.getMessage());
//            Toast.makeText(
//                    GpsService.contextService,
//                    e.getMessage(),
//                    Toast.LENGTH_SHORT).show();
            return false;
        } finally {
            return true;
        }
    }

    public void StopGPS() {
        bStarting = false;
        bGPSStarted = false;
        bServiceRunning = false;
        try {

            if (locationManager != null) {
                if (locationGPSListener != null) {
                    locationManager.removeUpdates(locationGPSListener);
                }
                if (locationNetListener != null) {
                    locationManager.removeUpdates(locationNetListener);
                }
                if (listener != null) {
                    locationManager.removeGpsStatusListener(listener);
                }
            }
            if (locationGPSListener != null) {
                locationGPSListener = null;
            }
            if (locationNetListener != null) {
                locationNetListener = null;
            }
            if (listener != null) {
                listener = null;
            }
            GpsService.this.stopSelf();
        } catch (Exception e) {

        } finally {
        }
    }

    GpsStatus.Listener listener = new GpsStatus.Listener() {
        @Override
        public void onGpsStatusChanged(int event) {
            switch (event) {
                //第一次定位
                case GpsStatus.GPS_EVENT_FIRST_FIX:
                    bStarting = false;
                    bGPSStarted = true;
                    break;
                //卫星状态改变
                case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                /*
                 Toast.makeText(getBaseContext(),"卫星状态改变", Toast.LENGTH_LONG).show();
                //获取当前状态
                GpsStatus gpsStatus=locationManager.getGpsStatus(null);
                //获取卫星颗数的默认最大值
                int maxSatellites = gpsStatus.getMaxSatellites();
                //创建一个迭代器保存所有卫星
                Iterator<GpsSatellite> iters = gpsStatus.getSatellites().iterator();
                int count = 0;
                while (iters.hasNext() && count <= maxSatellites) {
                    GpsSatellite s = iters.next();
                    count++;
                }
                Toast.makeText(getBaseContext(),
                		"搜索到："+count+"颗卫星", Toast.LENGTH_LONG).show();
               */
                    break;
                //定位启动
                case GpsStatus.GPS_EVENT_STARTED:
//                    Tip.shortTip("定位启动");
//                    Toast.makeText(GpsService.contextService,
//                            "定位启动", Toast.LENGTH_LONG).show();
                    break;
                //定位结束
                case GpsStatus.GPS_EVENT_STOPPED:
                    bStarting = false;
                    bGPSStarted = false;
//                    Tip.shortTip("定位终止");
//                    Toast.makeText(GpsService.contextService,
//                            "定位终止", Toast.LENGTH_LONG).show();
                    break;
            }
        }

        ;
    };

    //    private LocationListener locationGPSListener = new LocationListener() {
    private class MyLocationListner implements LocationListener {
        // 位置发生改变后调用
        @Override
        public void onLocationChanged(Location l) {
            if (l != null ) {
//                Log.d("type", "1111111111");

                updateWithNewLocation(l);

            }
        }

        // provider 被用户关闭后调用
        @Override
        public void onProviderDisabled(String provider) {
//            Tip.shortTip("GPS不可用");
//            Toast.makeText(GpsService.contextService,
//                    "GPS不可用", Toast.LENGTH_LONG).show();
        }

        // provider 被用户开启后调用
        @Override
        public void onProviderEnabled(String provider) {
//            Tip.shortTip("GPS启用");
//            Toast.makeText(GpsService.contextService,
//                    "GPS启用", Toast.LENGTH_LONG).show();
        }

        // provider 状态变化时调用
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            switch (status) {
                //GPS状态为可见时
                case LocationProvider.AVAILABLE:
//                    Tip.shortTip("当前GPS状态可用");
//                    Toast.makeText(GpsService.contextService,
//                            "当前GPS状态可用", Toast.LENGTH_LONG).show();
                    break;
                //GPS状态为服务区外时
                case LocationProvider.OUT_OF_SERVICE:
//                    Tip.shortTip("当前GPS状态为服务区外状态");
//                    Toast.makeText(GpsService.contextService,
//                            "当前GPS状态为服务区外状态", Toast.LENGTH_LONG).show();
                    break;
                //GPS状态为暂停服务时
                case LocationProvider.TEMPORARILY_UNAVAILABLE:
//                    Tip.shortTip("当前GPS状态为服务区外状态");
//                    Toast.makeText(GpsService.contextService,
//                            "当前GPS状态为服务区外状态", Toast.LENGTH_LONG).show();
                    break;
            }

        }

    };

//    private LocationListener locationNetListener = new LocationListener() {
//        // 位置发生改变后调用
//        public void onLocationChanged(Location l) {
//            if (l != null) {
//
//                Log.d("type", "22222222");
//                updateWithNewLocation(l);
//            }
//        }
//
//        // provider 被用户关闭后调用
//        public void onProviderDisabled(String provider) {
//            Tip.shortTip("GPS不可用");
////            Toast.makeText(GpsService.contextService,
////                    "GPS不可用", Toast.LENGTH_LONG).show();
//        }
//
//        // provider 被用户开启后调用
//        public void onProviderEnabled(String provider) {
//            Tip.shortTip("GPS启用");
////            Toast.makeText(GpsService.contextService,
////                    "GPS启用", Toast.LENGTH_LONG).show();
//        }
//
//        // provider 状态变化时调用
//        public void onStatusChanged(String provider, int status, Bundle extras) {
//            switch (status) {
//                //GPS状态为可见时
//                case LocationProvider.AVAILABLE:
//                    Tip.shortTip("当前GPS状态可用");
////                    Toast.makeText(GpsService.contextService,
////                            "当前GPS状态可用", Toast.LENGTH_LONG).show();
//                    break;
//                //GPS状态为服务区外时
//                case LocationProvider.OUT_OF_SERVICE:
//                    Tip.shortTip("当前GPS状态为服务区外状态");
////                    Toast.makeText(GpsService.contextService,
////                            "当前GPS状态为服务区外状态", Toast.LENGTH_LONG).show();
//                    break;
//                //GPS状态为暂停服务时
//                case LocationProvider.TEMPORARILY_UNAVAILABLE:
//                    Tip.shortTip("当前GPS状态为服务区外状态");
////                    Toast.makeText(GpsService.contextService,
////                            "当前GPS状态为服务区外状态", Toast.LENGTH_LONG).show();
//
//                    break;
//            }
//
//        }
//
//    };

    private void updateWithNewLocation(final Location loc) {
        Log.d("dingwei","定位");
        try {
//            type = ClientConfig.getStringConfig("type", "Gps");
//            UserId = XunjianApplication.instance.currentLoginUser.getID();
            if (loc != null ) {
//            if (loc != null && loc.getLatitude() !=0 && loc.getLongitude() != 0 ) {
                //RecordGPS();
                final double lat = loc.getLatitude();
                final double lon = loc.getLongitude();

                Log.d("dingwei", lat + "---------------" + lon);
//                XunjianApplication.getInstance().putTemp("gps_lat",String.valueOf(lat));
//                XunjianApplication.getInstance().putTemp("gps_lon",String.valueOf(lon));
//                Log.d("zuobiao", provider+"");
//                GaussConvert convert = new GaussConvert(3,36,-0.000509904056696209,-0.00360088278565851,-0.0136248739300601,-0.000287807290858987,3272688.03445991,-140014.42506602,69289.6714,62940.1026);



                 GPSPoint pt = new GPSPoint(lat, lon);
                if (GpsList.size()< 5){
                    GpsList.add(pt);
                }else {

                    ChooseThread ct =new ChooseThread(getApplicationContext(),GpsList);
                    ct.start();
                    GpsList = new ArrayList<>();
                }






//                GPSPoint ptNew = convert.WGS84ToLocal(pt);//坐标转换
                //serviceͨ��㲥������Ϣ��activity
//                CustomApplication.getInstance().eventBus.post(new GpsMessage(lat, lon));//定位信息
//                Log.d("type", type);
//                if (GpsService.GPS_TYPE_XJ.equals(type)) {
//                    // 获取经纬度,然后发送信息到服务器
////                                if (gps != null) { // 当结束服务时gps为空
////                                     获取经纬度
////                                Location location = loc;
//                    Task task = XunjianApplication.instance.taskManager.getTask();
//                    taskid = Integer.valueOf(task.get任务ID());
//                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                    java.util.Date curDate = new java.util.Date(System.currentTimeMillis());// 获取当前时间
//                    final String date = formatter.format(curDate);
////                                double lat = loc.getLatitude();
////                                double lon = loc.getLongitude();
//
//                    try {
//                        final Dao<XunjianDian, Integer> xjdDao = databaseHelper.get巡检点Dao();
//                        XunjianDian last = xjdDao.queryBuilder().orderBy("LID", false).queryForFirst();
//                        int LID = 0;
//                        if (last != null) {
//                            LID = last.getLID();
//                        }
//                        int newLID = LID + 1;
//                        Log.d("LID", String.valueOf(newLID));
//                        XunjianDian dian = new XunjianDian();
//                        dian.set任务ID(taskid);
//                        dian.set用户ID(UserId);
//                        dian.setY(new BigDecimal(String.valueOf(lat)));
//                        dian.setX(new BigDecimal(String.valueOf(lon)));
//                        dian.set时间(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date));
//                        dian.set数据状态(DataStatus.Inserted);
//                        xjdDao.create(dian);
//                        Log.d("巡检记录", " 巡检点");
//                        DataSyncHelper.getInstance().uploadSync(DataTables.巡检点表);//数据上传
//                        Log.d("巡检记录", " 巡检点数据上传");
//
//                        Dao<XunjiandianGongzuo, Integer> xjDao = databaseHelper.get选检点工作Dao();
//
//                        List<XunjiandianGongzuo> xjds = xjDao.queryBuilder().where().eq("任务ID", taskid).and().eq("巡检时间", "").query();
//
//                        for (XunjiandianGongzuo xjd : xjds) {
//                            double x = xjd.get坐标X().doubleValue();
//                            double y = xjd.get坐标Y().doubleValue();
////                                      double legth = Math.sqrt((x - lat) * (x - lat) + (y - lon) * (y - lon));
//                            double legth = getDistance(x, y, lon, lat);
//                            //获取坐标 与巡检工作点表坐标对比 距离小于20 更改 巡检时间
//                            if (legth <= 20) {
//                                int xjdID = xjd.getID();
//                                //更新 巡检工作点表 巡检时间
//                                xjd.set巡检时间(date);
//                                //设置数据状态  上传到服务器
//                               int bb =  xjd.get版本()+1;
//                                xjd.set版本(bb);
//                                xjd.set数据状态(DataStatus.Updated);
//                                xjDao.update(xjd);
//                                Log.d("巡检记录", " 巡检工作点");
//                                DataSyncHelper.getInstance().uploadSync(DataTables.巡检点工作表);//数据上传
//                                CustomApplication.getInstance().eventBus.post(new MAMessage(MAMessage.CurrentCommand_XJGZD));//定位信息
//
//
//                                //更新 排班表的 已巡点数
//                                Dao<PaiBan, Integer> pbDao = databaseHelper.get排班Dao();
//                                PaiBan ban = pbDao.queryBuilder().where().eq("ID", String.valueOf(taskid)).queryForFirst();
//                                int yixds = ban.get已巡点数();
//                                final int yxds = yixds + 1;
//                                ban.set已巡点数(yxds);
//                                int bb_b =  ban.get版本()+1;
//                                ban.set版本(bb_b);
//                                ban.set数据状态(DataStatus.Updated);
//
//                                pbDao.update(ban);
//
////                                DataSyncHelper.getInstance().uploadSync(DataTables.排班表);
//                                int yxds_new = ban.get已巡点数();
//                                int yingxds_new = ban.get应巡点数();
//                                if (yxds_new == yingxds_new){
//                                    //巡检状态已完成
//                                    ban.set执行状态("已完成");
//                                    ban.set是否历史("是");
//                                    ban.set数据状态(DataStatus.Updated);
//                                    pbDao.update(ban);
//                                    Log.d("巡检记录", " 线路已完成");
////                                  Xnew StickTip("当前任务已完成！！").show();
//                                    Tip.longTip("当前任务已完成！！");
//                                    XunjianApplication.instance.eventBus.post(MAMessage.CurrentCommand_TZDW);
//                                }else {
//
//                                }
//                                DataSyncHelper.getInstance().uploadSync(DataTables.排班表);
//                            }
//                        }
//                    } catch (SQLException e) {
//                        e.printStackTrace();
//                    } catch (ParseException e) {
//                        e.printStackTrace();
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
            } else {
                Log.d("error", "无定位信息");
            }
        } catch (Exception e) {
//            Tip.shortTip(e.getMessage());//提示消息
            Log.d("dingwei",e.getMessage());

        } finally {

        }
    }


    //接收过后的点 保存
//    @Subscribe
//    public void getCPoint( ChooseMessage msg) {
//
////                GPSPoint ptNew = convert.WGS84ToLocal(pt);//坐标转换
//        //serviceͨ��㲥������Ϣ��activity
//        double lat = msg.getPoint().x;
//        double lon = msg.getPoint().y;
//        CustomApplication.getInstance().eventBus.post(new GpsMessage(lat, lon));//定位信息
//
//
//        Log.d("type", type);
//        if (GpsService.GPS_TYPE_XJ.equals(type)) {
//            // 获取经纬度,然后发送信息到服务器
////                                if (gps != null) { // 当结束服务时gps为空
////                                     获取经纬度
////                                Location location = loc;
//            Task task = XunjianApplication.instance.taskManager.getTask();
//            taskid = Integer.valueOf(task.get任务ID());
//            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            java.util.Date curDate = new java.util.Date(System.currentTimeMillis());// 获取当前时间
//            final String date = formatter.format(curDate);
////                                double lat = loc.getLatitude();
////                                double lon = loc.getLongitude();
//
//            try {
//                final Dao<XunjianDian, Integer> xjdDao = databaseHelper.get巡检点Dao();
//                XunjianDian last = xjdDao.queryBuilder().orderBy("LID", false).queryForFirst();
//                int LID = 0;
//                if (last != null) {
//                    LID = last.getLID();
//                }
//                int newLID = LID + 1;
//                Log.d("LID", String.valueOf(newLID));
//                XunjianDian dian = new XunjianDian();
//                dian.set任务ID(taskid);
//                dian.set用户ID(UserId);
//                dian.setY(new BigDecimal(String.valueOf(lat)));
//                dian.setX(new BigDecimal(String.valueOf(lon)));
//                dian.set时间(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date));
//                dian.set数据状态(DataStatus.Inserted);
//                xjdDao.create(dian);
//                Log.d("巡检记录", " 巡检点");
//                if (XunjianApplication.instance.networked){
//
//                    DataSyncHelper.getInstance().uploadSync(DataTables.巡检点表);//数据上传
//                }
//                Log.d("巡检记录", " 巡检点数据上传");
//
//                Dao<XunjiandianGongzuo, Integer> xjDao = databaseHelper.get选检点工作Dao();
//
//                List<XunjiandianGongzuo> xjds = xjDao.queryBuilder().where().eq("任务ID", taskid).and().eq("巡检时间", "").query();
//
//                for (XunjiandianGongzuo xjd : xjds) {
//                    double x = xjd.get坐标X().doubleValue();
//                    double y = xjd.get坐标Y().doubleValue();
////                   double legth = Math.sqrt((x - lat) * (x - lat) + (y - lon) * (y - lon));
//                    double legth = getDistance(x, y, lon, lat);
//                    //获取坐标 与巡检工作点表坐标对比 距离小于20 更改 巡检时间
//                    if (legth <= 20) {
//                        int xjdID = xjd.getID();
//                        //更新 巡检工作点表 巡检时间
//                        xjd.set巡检时间(date);
//                        //设置数据状态  上传到服务器
//                        int bb =  xjd.get版本()+1;
//                        xjd.set版本(bb);
//                        xjd.set数据状态(DataStatus.Updated);
//                        xjDao.update(xjd);
//                        Log.d("巡检记录", " 巡检工作点");
//                        if (XunjianApplication.instance.networked) {
//
//                            DataSyncHelper.getInstance().uploadSync(DataTables.巡检点工作表);//数据上传
//                        }
//                        CustomApplication.getInstance().eventBus.post(new MAMessage(MAMessage.CurrentCommand_XJGZD));//定位信息
//
//
//                        //更新 排班表的 已巡点数
//                        Dao<PaiBan, Integer> pbDao = databaseHelper.get排班Dao();
//                        PaiBan ban = pbDao.queryBuilder().where().eq("ID", String.valueOf(taskid)).queryForFirst();
//                        int yixds = ban.get已巡点数();
//                        final int yxds = yixds + 1;
//                        ban.set已巡点数(yxds);
//                        int bb_b =  ban.get版本()+1;
//                        ban.set版本(bb_b);
//                        ban.set数据状态(DataStatus.Updated);
//
//                        pbDao.update(ban);
//
////                                DataSyncHelper.getInstance().uploadSync(DataTables.排班表);
//                        int yxds_new = ban.get已巡点数();
//                        int yingxds_new = ban.get应巡点数();
//                        if (yxds_new == yingxds_new){
//                            //巡检状态已完成
//                            ban.set执行状态("已完成");
//                            ban.set是否历史("是");
//                            ban.set数据状态(DataStatus.Updated);
//                            pbDao.update(ban);
//                            Log.d("巡检记录", " 线路已完成");
////                                  Xnew StickTip("当前任务已完成！！").show();
//                            Tip.longTip("当前任务已完成！！");
//                            XunjianApplication.instance.eventBus.post(MAMessage.CurrentCommand_TZDW);
//                        }else {
//
//                        }
//                        if (XunjianApplication.instance.networked) {
//
//                            DataSyncHelper.getInstance().uploadSync(DataTables.排班表);
//                        }
//                    }
//                }
//            } catch (SQLException e) {
//                e.printStackTrace();
//            } catch (ParseException e) {
//                e.printStackTrace();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//
//    }



    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    //经纬度点 求距离
    public static double getDistance(double lat1, double lon1, double lat2, double lon2) {
        double radLat1 = lat1 * Math.PI / 180;
        double radLat2 = lat2 * Math.PI / 180;
        double a = radLat1 - radLat2;
        double b = lon1 * Math.PI / 180 - lon2 * Math.PI / 180;
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378137.0;// 取WGS84标准参考椭球中的地球长半径(单位:m)
        s = Math.round(s * 10000) / 10000;
        return s;
    }
}
